package com.sky.service.impl;

import com.github.pagehelper.PageHelper;
import com.sky.anno.CleanCache;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.enumeration.DataType;
import com.sky.enumeration.OperationType;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.github.pagehelper.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    /**
     * 功能描述: 菜品分页
     * 两个表联合查询,查询出来的数据拷贝到vo,由于vo没有设置菜品分类名称
     * 需要遍历map取出每个菜品id
     * 根据菜品的id去category表查询.菜品分类名称
     * 设置的到vo属性上
     *
     * @return : com.sky.result.PageResult
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        /*PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<Dish> page = dishMapper.page(dishPageQueryDTO);
        List<DishVO> recodes = page.getResult().stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            String nameByCategoryId = categoryMapper.findNameByCategoryId(dish.getCategoryId());
            dishVO.setCategoryName(nameByCategoryId);
            return dishVO;
        }).collect(Collectors.toList());
        return new PageResult(page.getTotal(), recodes);*/
        /*PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<Dish> page = dishMapper.page(dishPageQueryDTO);
        List<DishVO> collect = page.getResult().stream().map(dish -> {
            Long categoryId = dish.getCategoryId();
            String nameByCategoryId = categoryMapper.findNameByCategoryId(categoryId);
            DishVO dishVO = new DishVO();
            dishVO.setCategoryName(nameByCategoryId);
            return dishVO;
        }).collect(Collectors.toList());
        return new PageResult(page.getTotal(),collect);*/
        /*PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<Dish> page = dishMapper.page(dishPageQueryDTO);
        List<DishVO> collect = page.getResult().stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            Long categoryId = dish.getCategoryId();
            String nameByCategoryId = categoryMapper.findNameByCategoryId(categoryId);
            dishVO.setCategoryName(nameByCategoryId);
            return dishVO;
        }).collect(Collectors.toList());
        return new PageResult(page.getTotal(),collect);*/
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<Dish> page = dishMapper.page(dishPageQueryDTO);
        List<DishVO> collect = page.getResult().stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            Long categoryId = dish.getCategoryId();
            String nameByCategoryId = categoryMapper.findNameByCategoryId(categoryId);
            dishVO.setCategoryName(nameByCategoryId);
            return dishVO;
        }).collect(Collectors.toList());
        return new PageResult(page.getTotal(), collect);
    }

    /**
     * 功能描述: 批量删除
     *
     * @return : boolean
     */
    @Transactional
    @Override
    public void delete(List<Long> ids) {
        ids.forEach(id -> {
            //去数据库查询菜品,判断状态是否为停售
            Dish dish = dishMapper.findById(id);
            //起售中,不能删
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            //根据菜品id查询套餐
            List<Long> setmealIdsByDishId = setmealDishService.findSetmealIdsByDishId(id);
            //菜品关联的套餐不能删除
            if (setmealIdsByDishId == null && setmealIdsByDishId.size() > 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        });
        //批量删除口味信息
        dishFlavorMapper.deleteByDishIds(ids);
        //批量删除菜品
        dishMapper.delete(ids);

    }

    /**
     * 功能描述: 根据菜品id查询菜品信息
     *
     * @return : com.sky.entity.Dish
     */
    @Override
    public Dish findById(Long id) {
        Dish dishMapperById = dishMapper.findById(id);
        return dishMapperById;
    }

    /**
     * 功能描述: 添加菜品
     *
     * @return : void
     */
    @Transactional
    @Override
    @CleanCache(dataType = DataType.DISH, opType = OperationType.INSERT)
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //保存菜品后返回菜品id
        dishMapper.save(dish);
        Long id = dish.getId();
        List<DishFlavor> collect = dishDTO.getFlavors().stream().map(dishFlavor -> {
            dishFlavor.setDishId(id);
            return dishFlavor;
        }).collect(Collectors.toList());
        dishFlavorMapper.saveBatchFlavoies(collect);
    }

    /**
     * 功能描述: 菜品停售起售
     *
     * @return : com.sky.result.Result
     */
    public void editStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);
    }

    /**
     * 功能描述: 菜品修改
     *
     * @return : void
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        Long id = dish.getId();
        ArrayList<Long> ids = new ArrayList<>();
        ids.add(id);
        //起售的菜品不允许修改
        //根据菜品id查询状态
        Dish byId = dishMapper.findById(dishDTO.getId());
        if (byId.getStatus() == StatusConstant.ENABLE) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE_CANNOT_UPDATING);
        }
        //删除口味,在进行修改
        dishFlavorMapper.deleteByDishIds(ids);
        //修改口味
        dishMapper.update(dish);
    }

    /**
     * 功能描述: 根据菜品类型id查询菜品
     *
     * @return : java.util.List<com.sky.entity.Dish>
     */
    @Override
    public List<Dish> findDishByCategoryId(Long categoryId) {
        List<Dish> dishByCategoryId = dishMapper.findDishByCategoryId(categoryId);
        return dishByCategoryId;
    }

    /**
     * 条件查询菜品和口味
     *
     * @param dishDTO
     * @return
     */
    public List<DishVO> listWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.findByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
